package cn.ddm.hrm.service.impl;

import cn.ddm.hrm.constants.LoginConstants;
import cn.ddm.hrm.domain.LoginUser;
import cn.ddm.hrm.dto.LoginDto;
import cn.ddm.hrm.exception.ErrorCode;
import cn.ddm.hrm.exception.ValidUtils;
import cn.ddm.hrm.mapper.LoginUserMapper;
import cn.ddm.hrm.mapper.OauthClientDetailsMapper;
import cn.ddm.hrm.properties.Oauth2ClientDetails;
import cn.ddm.hrm.properties.Oauth2ClientDetailsProperties;
import cn.ddm.hrm.service.ILoginUserService;
import cn.ddm.hrm.util.AjaxResult;
import cn.ddm.hrm.util.HttpUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ldm
 * @since 2022-01-02
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {

    @Autowired
    private LoginUserMapper loginUserMapper;

    @Autowired
    private Oauth2ClientDetailsProperties properties;


    @Override
    public AjaxResult loginAccount(LoginDto loginDto) {
        // 参数校验
        String username = loginDto.getUsername();
        Integer type = loginDto.getType();
        // 查询参数
        List<LoginUser> loginUsers = loginUserMapper.selectList(
                new EntityWrapper<LoginUser>()
                        .eq("username", username)
                        .or().eq("phone", username)
                        .or().eq("email", username)
        );
        ValidUtils.assertListNotNull(loginUsers, ErrorCode.CODE_400_AUTH_EQUAL);

        // 发送请求

        // 查询oauth_client_details信息
        Oauth2ClientDetails clientDetials = properties.getClientDetials(type);
        ValidUtils.assertNull(clientDetials, ErrorCode.CODE_400_COURSE_GRADE_ILLEGAL);
        String url = String.format(LoginConstants.PASSWORD_AUTH_URL, clientDetials.getClientId(), clientDetials.getSecret(), loginDto.getUsername(), loginDto.getPassword());
        // 发送请求
        Map<String, Object> map = HttpUtil.sendPost(url);

        //错误判断
        String error = (String) map.get("error");
        String message = (String) map.get("error_description");
        ValidUtils.assertNull(error,message);


        //成功后获取token和refreshToken
        String token = (String) map.get("access_token");
        String refreshToken = (String) map.get("refresh_token");

        //构造返回值
        HashMap<String, String> result = new HashMap<>();
        result.put("token",token);
        result.put("refreshToken",refreshToken);
        return AjaxResult.me().setResultObj(result);

    }
}
